<template>
  <div id="video-container"> </div>
</template>

<script>
import Aliplayer from 'aliyun-aliplayer';
import 'aliyun-aliplayer/build/skins/default/aliplayer-min.css';
import { getToken } from '@/utils/auth';
export default {
  name: 'VideoPlayer',
  inheritAttrs: false,
  props: {
    // 视频源地址
    modelValue: {
      type: String,
      default: ''
    },
    // 视频封面地址
    cover: {
      type: String,
      default: ''
    },
    // 视频播放器宽度
    width: {
      type: String,
      default: '100%'
    },
    // 视频播放器高度
    height: {
      type: String,
      default: '500px'
    },
    // 是否自动播放
    autoplay: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => {}
    },
    oncePlay: {
      type: Function,
      default: undefined
    },
    ended: {
      type: Function,
      default: undefined
    }
  },
  data() {
    return {
      player: null,
      hasPlayed: false // 用于记录视频是否已经播放过
    };
  },
  watch: {
    modelValue: {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.initPlayer();
          });
        }
      },
      immediate: true
    }
  },
  mounted() {
    // this.initPlayer();
  },
  methods: {
    initPlayer() {
      const cover = this.formData && this.cover ? this.formData[this.cover] : '';
      this.player = new Aliplayer({
        id: 'video-container',
        width: this.width,
        height: this.height,
        source: this.modelValue,
        cover,
        autoplay: this.autoplay
      });
      this.handlePlayerListen();
    },
    handlePlayerListen() {
      if (this.ended && typeof this.ended === 'function') {
        this.player.on('ended', () => {
          this.ended();
        });
      }
      if (this.oncePlay && typeof this.oncePlay === 'function') {
        this.player.on('play', () => {
          if (!this.hasPlayed) {
            this.hasPlayed = true;
            this.oncePlay();
          }
        });
      }
    }
  }
};
</script>